//
//  HomeDetailViewController.swift
//  AgricultureApp
//
//  Created by eport_user1 on 2018/1/15.
//  Copyright © 2018年 eport_user1. All rights reserved.
//

import UIKit
import WebKit

class HomeDetailViewController: BaseViewController {

    var model : HomeModel? {
        didSet {
            var url = ""
            
            let typeStr = model?.type
            if (typeStr == ModelType.product) {
                url = WebProduct
            } else if (typeStr == ModelType.productNews) {
                url = WebProductNews
            } else if (typeStr == ModelType.productCases) {
                url = WebProductCases
            } else if (typeStr == ModelType.productVideo) {
                url = WebProductVideo
            } else if (typeStr == ModelType.farmNews) {
                url = WebFarmNews
            }
            
            
            
            url = url.appendingFormat("%d", (model?.newsId)!)
            
            self.webview.load(URLRequest.init(url: URL.init(string: url)!))
        }
    }

    
    lazy var webview:WKWebView = {
        
        let web = WKWebView.init(frame: kScreenBounds)
        return web
    }()
    
    fileprivate let active : UIActivityIndicatorView = {
        let act : UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        act.frame = CGRect.init(x: kScreenWidth/2 - 20, y: kScreenHeight/2 - 20, width: 40, height: 40)
        return act
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        
        webview.navigationDelegate = self
        webview.allowsBackForwardNavigationGestures = true
        self.view.addSubview(webview)
        self.view.addSubview(active)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    

}

extension HomeDetailViewController{
    
    func setupNav() -> Void {
        
        view.backgroundColor = UIColor.white
        title = "详情"
    }
    
}


//MARK: 代理
extension HomeDetailViewController:WKNavigationDelegate{
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        self.active.startAnimating()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.active.stopAnimating()
        
        webView.evaluateJavaScript("document.title") { (title : Any?, err : Error?) in
            self.title = title as? String
        }
        
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        self.active.stopAnimating()
    }

    
    
}



